const CONFIG = require('../../libs/config.js')
const AUTH = require('../../utils/auth')
const UserApi = require('../../libs/user')
const APP = getApp()
APP.configLoadOK = () => {

}

Page({
  data: {
    nick: undefined,
  },
  onLoad() {
    
  },
  onShow() {
    // 先用AUTH检查用户是否登录
    AUTH.checkHasLogined().then(isLogined => {
      // console.log("输出" + isLogined)
      if (isLogined) {
        this.getUserInfo()
      } else {
        AUTH.authorize().then(res => {
          //先认证，然后绑定卖方?
          this.onShow()
        })
      }
    })
  },
  async getUserInfo() {
    console.log("获取用户信息去")
    UserApi.getUserInfo().then(res => {
      const _data = {}
      _data.UserInfoMap = res.data.data
      _data.nick = res.data.data.nick
      this.setData(_data)
    })
  },
  scanOrderCode() {
    wx.scanCode({
      onlyFromCamera: true,
      success(res) {
        wx.navigateTo({
          url: '/pages/order-details/scan-result?hxNumber=' + res.result,
        })
      },
      fail(err) {
        console.error(err)
        wx.showToast({
          title: err.errMsg,
          icon: 'none'
        })
      }
    })
  },
  //清空所有缓存，导致我总是获取不到token 
  // clearStorage() {
  //   wx.clearStorageSync()
  //   wx.reLaunch({
  //     url: '/pages/index/index',
  //   })
  // },
  editNick() {
    this.setData({
      nickShow: true
    })
  },
  async _editNick() {
    console.log("获取输入昵称: " + this.data.nick)
    if (!this.data.nick) {
      wx.showToast({
        title: '请填写昵称',
        icon: 'none'
      })
      return
    }
    // console.log("获取输入昵称: " + this.data.nick)

    // const res = UserApi.updateUserNick(this.data.nick)
    UserApi.updateUserNick(this.data.nick).then(res => {
      const _data = {}
      _data.UserInfoMap = res.data.data
      _data.nick = res.data.data.nick
      this.setData(_data)
      if (res.code != 200) {
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
        return
      }
      wx.showToast({
        title: '设置成功',
      })
    })
  },

  //选择头像功能
  async onChooseAvatar(e) {
    console.log(e);
    const avatarUrl = e.detail.avatarUrl
    console.log("获取token:" + wx.getStorageSync('token') + "图片:" + avatarUrl)
    wx.uploadFile({
      url: CONFIG.Config.url + '/upload',
      filePath: avatarUrl,
      name: 'file',
      header: {
        token: wx.getStorageSync('token'),
      },
      success(res) {
        // md返回的成字符串而不是Json
        console.log(res.data)
        if (res.statusCode == 200) {
          wx.showToast({
            title: '设置成功',
          })
        }
      }
    })
    //再重新获取用户信息
    // this.getUserApiInfo()
  },
})